import { Button, Radio, FormInstance, DatePicker } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ProFormFieldSet } from '@ant-design/pro-form';
import StatisticsCard from '@/components/StatisticsCard/Index';
import './style.less'
import BreadcrumbDept from '@/components/BreadcrumbDept';
import { getRentSaleDataForDetail, downRentSaleDataForDetail } from '@/services/report/api'; 
import { subtractDays, currentDate, isNull, showMsg } from '@/utils/utils';
import moment from 'moment';
import PermissionControl from '@/components/PermissionControl';
import './style.less'

const StockList: React.FC = () => {
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [detail, setDetail] = useState({});
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});

  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '统计周期',
      dataIndex: 'rangedate',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return (<ProFormFieldSet style={{gap: 2}}>
            <DatePicker allowClear={false} style={{width: '100%'}} />
              <span style={{padding: '0 5px'}}>-</span>
            <DatePicker allowClear={false} style={{width: '100%'}} />
          </ProFormFieldSet>
        );
      }
    },
    {
      title: '物品名称',
      dataIndex: 'goodsName',
      fieldProps: {
        placeholder: '输入物品名称',
      },
      // width: 120,
    },
    {
      title: '住院号',
      dataIndex: 'admissionNum',
      fieldProps: {
        placeholder: '输入住院号',
      },
    },
    {
      title: '患者姓名',
      dataIndex: 'patientName',
      fieldProps: {
        placeholder: '输入患者姓名',
      },
    },
    {
      title: '租赁方式',
      dataIndex: 'leaseCycle',
      search: false,
    },
    {
      title: '周期长度',
      dataIndex: 'cycleNum',
      search: false,
      align: 'right',
    },
    {
      title: '未结算金额',
      dataIndex: 'usettPrice',
      search: false,
      align: 'right',
      valueType: 'money',
    },
    {
      title: '已结算金额',
      dataIndex: 'psettPrice',
      search: false,
      align: 'right',
      valueType: 'money',
    },
    {
      title: '统计方式',
      dataIndex: 'sumFlag',
      hideInTable: true,
      valueType: 'radio',
      renderFormItem: () => {
        return <Radio.Group options={[
          {
            label: '按服务周期统计',
            value: 'P'
          },
          {
            label: '按结算周期统计',
            value: 'C'
          }
        ]}>

        </Radio.Group>;
      }
    }
  ];


  useEffect(() => {
    formRef.current?.setFieldsValue({
      rangedate: [subtractDays(30), '-', currentDate()],
      sumFlag: 'P'
    });
    formRef.current?.submit();
  }, [])

  const getList = async(params: any) => {
    try {
      console.log('params', params)
      params.begin_date_str = moment(params.rangedate[0]).format('YYYYMMDD');
      params.end_date_str = moment(params.rangedate[2]).format('YYYYMMDD');
      const data = await getRentSaleDataForDetail(params);
      setDetail(data);
      setSearchParams(params);
      return {
        data: data.record_list,
        success: true,
        total: data.sum_record_num
      }
    } catch (error) {
      showMsg(error?.data?.errmsg); 
      return {
        data: [],
        success: true,
        total: 0
      };
    }
  }

  const download = async() => {
    setLoading(true);
    await downRentSaleDataForDetail(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }


  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<STOCKGOODSAPI.GoodsItem, STOCKGOODSAPI.GoodsItem & COMMON.PageParams>
        formRef={formRef}
        actionRef={actionRef}
        rowKey="goods_id"
        bordered
        manualRequest
        className="custome-table"
        search={{
          span: 8,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              ...dom,
              <PermissionControl action_id="700704001">
                <Button key="export" type="primary" loading={loading} disabled={isNull(detail.record_list)} onClick={download}>导出报表</Button>
              </PermissionControl>
            ]
          }
        }}
        request={getList}
        columns={columns}
        options={false}
        tableExtraRender={(_, data) => (
          <div className='StatisticsCard' style={{ background: '#fff', padding: 12 }}>
            <div style={{marginBottom: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
              <StatisticsCard iconType="database" title="租赁物品种类" number={detail.goodsTypeNum} />
              <StatisticsCard title="租赁患者数" iconType="database" number={detail.patientNum} />
              <StatisticsCard title="未结算金额" number={`￥${detail.totalUSettPrice}`}/>
              <StatisticsCard style={{marginRight: 0}} title="已结算金额" number={`￥${detail.totalPSettPrice}`} />
            </div>
          </div>
        )}
      />
    </PageContainer>
  );
};
export default StockList;
